package com.atguigu.flink.cep;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.functions.PatternProcessFunction;
import org.apache.flink.cep.functions.TimedOutPartialMatchHandler;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * Created by Smexy on 2022/12/20
 *
 *
 *
 */
public class Demo11_TimeOutProcess
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((e, r) -> e.getTs());


        SingleOutputStreamOperator<WaterSensor> ds =
            env.readTextFile("data/ceptimeout.txt")
               .map(new WaterSensorMapFunction())
               .assignTimestampsAndWatermarks(watermarkStrategy);


        Pattern<WaterSensor, WaterSensor> pattern = Pattern.<WaterSensor>begin("s1")
            .where(new SimpleCondition<WaterSensor>()
            {
                //定义匹配规则
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "s1".equals(value.getId());
                }
            })
            //下一条必须在2s内到达，不含2s
            .within(Time.seconds(2))
            .next("s2")
            .where(new SimpleCondition<WaterSensor>()
            {
                //定义匹配规则
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "s2".equals(value.getId());
                }
            })
            ;


        PatternStream<WaterSensor> patternStream = CEP.pattern(ds, pattern);

        OutputTag<String> outputTag = new OutputTag<>("timeout", TypeInformation.of(String.class));


        SingleOutputStreamOperator<String> result = patternStream.process(new MyProcess());

        result.getSideOutput(outputTag).printToErr("超时");
        //匹配成功，未超时
        result.print().setParallelism(1);


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private static class MyProcess  extends PatternProcessFunction<WaterSensor, String> implements TimedOutPartialMatchHandler<WaterSensor>{

        //处理未超时，匹配到的数据
        @Override
        public void processMatch(Map<String, List<WaterSensor>> match, Context ctx, Collector<String> out) throws Exception {
                out.collect(match.toString());
        }

        //处理超时的数据
        @Override
        public void processTimedOutMatch(Map<String, List<WaterSensor>> match, Context ctx) throws Exception {
            //输出到侧流
            ctx.output(new OutputTag<String>("timeout",TypeInformation.of(String.class)),match.toString());

        }
    }
}
